package chai.ningning.myself;

public class SimulationBank {
    private int balance = 500;

    public int getBalance() {
        return balance;
    }
    public synchronized void withdrawal(int amount){//取款
        balance -= amount;
    }

    static class BankThread implements Runnable{

        private SimulationBank sBank = new SimulationBank();
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                makewithdrawal(100);
            }
        }
        private synchronized void makewithdrawal(int amount){
            if (sBank.getBalance() >= amount) {
                System.out.println(Thread.currentThread().getName() + "准备取款");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sBank.withdrawal(amount);
                System.out.println(Thread.currentThread().getName() + "取款完成");
            }else {
                System.out.println("余额不足"+Thread.currentThread().getName()+"的取款，余额为："+sBank.getBalance());
                System.exit(0);
            }
        }
    }

    public  static void main(String[] args) {
        Runnable r = new BankThread();

        Thread first = new Thread(r);
        Thread second = new Thread(r);
        first.setName("秦时");
        second.setName("明月");
        first.start();
        second.start();
    }
}
